package cn.itsource.consumer.direct;

import cn.itsource.utils.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @description: 消费者
 */
public class Consumer2 {
    public static final String EXCHANGE_DIRECT = "exchange_direct";

    public static final String QUEUE_DIRECT_2 = "queue_direct_2";

    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、创建队列
     * 4、绑定队列到交换机
     * 5、监听队列
     * 6、处理消息
     */
    public static void main(String[] args) throws Exception {
        //1、创建连接
        Connection connection = ConnectionUtil.getConnection();
        //2、创建信道
        Channel channel = connection.createChannel();

        //设置消息并发处理数量
        channel.basicQos(1);

        //3、创建队列
        channel.queueDeclare(QUEUE_DIRECT_2, true, false, false, null);

        //4、绑定队列到交换机
        channel.queueBind(QUEUE_DIRECT_2, EXCHANGE_DIRECT, "error");
        channel.queueBind(QUEUE_DIRECT_2, EXCHANGE_DIRECT, "debug");

        //5、监听队列
        channel.basicConsume(QUEUE_DIRECT_2, false, new DefaultConsumer(channel){
            //6、处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我是消费者Consumer2，收到消息：" + new String(body));
                //手动签收
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}